package com.cgnpc.scp.config;

import com.cgnpc.scp.common.utils.StringUtil;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/******************************
 * 用途说明: 
 * 作者姓名: chenshijie
 * 创建时间: 2020/10/04 11:37
 ******************************/
@Component
public class MockClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MockClient.class);
//https://scp.cgnpc.com.cn/app-api"
    private static final String TEST_ENV = "https://scp-t.cgnpc.com.cn/app-api/scp/agent/adapter/outer";

//    private static final String TEST_ENV = "http://127.0.0.1:8089/scp/agent/adapter/outer";

    @Autowired
    private RestTemplate restTemplate;

    /**
     *  支持token由前端传入
     */
    public <T> T invoke( String beanName, String methodName, List params, Class<T> returnType, Class... paramsType) {
        return invoke(null, beanName, methodName, params, returnType, paramsType);
    }

    public <T> T invoke(HttpServletRequest request,String beanName, String methodName, List params, Class<T> returnType, Class... paramsType ) {
        MockParam mockParam = new MockParam();
        mockParam.setBeanName(beanName);
        mockParam.setMethodName(methodName);
        mockParam.setParams(params);
        mockParam.setParamsType(paramsType);
        T response = null;
        try {
            String token = null;
            if(request != null){
                token = request.getHeader("token");
            }
            HttpHeaders headers = new HttpHeaders();
            if(!StringUtil.isNullOrSpace(token)){
                headers.add("token", token);
            }

            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<MockParam> requestEntity = new HttpEntity<>(mockParam, headers);
            response = restTemplate.postForObject(TEST_ENV, requestEntity, returnType);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("MockClient invoke error.", e);
        }
        return response;
    }
}
